package cn.cjj.gulimall.product.service.impl;

import cn.cjj.gulimall.product.entity.SkuImagesEntity;
import cn.cjj.gulimall.product.entity.SpuInfoDescEntity;
import cn.cjj.gulimall.product.service.*;
import cn.cjj.gulimall.product.vo.SkuItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cjj.common.utils.PageUtils;
import cn.cjj.common.utils.Query;

import cn.cjj.gulimall.product.dao.SkuInfoDao;
import cn.cjj.gulimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntities) {
        this.save(skuInfoEntities);
    }

    //page: 1,//当前页码
    //limit: 10,//每页记录数
    //sidx: 'id',//排序字段
    //order: 'asc/desc',//排序方式
    //key: '华为',//检索关键字
    //catelogId: 0,
    //brandId: 0,
    //min: 0,
    //max: 0
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId)) {
            if (!"0".equals(catelogId)) {
                wrapper.eq("catalog_id", catelogId);
            }
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId)) {
            if (!"0".equals(brandId)) {
                wrapper.eq("brand_id", brandId);
            }
        }
        String min = (String) params.get("min");
        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(min)) {
            wrapper.ge("price", min);
        }
        if (StringUtils.isNotEmpty(max)) {
            try {
                BigDecimal maxBigDecimal = new BigDecimal(max);
                if (maxBigDecimal.compareTo(new BigDecimal(0)) > 0) {
                    wrapper.le("price", maxBigDecimal);
                }
            } catch (Exception ignored) {

            }

        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuId);
        List<SkuInfoEntity> skuInfoEntities = this.list(wrapper);

        return skuInfoEntities;
    }

    @Override
    public SkuItemVo getItemInfoById(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItem = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = this.getById(skuId);
            skuItem.setInfo(skuInfo);
            return skuInfo;
        }, executor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(info -> {
            Long spuId = info.getSpuId();

            List<SkuItemVo.SkuItemSaleAttrVo> skuItemSaleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
            skuItem.setSaleAttr(skuItemSaleAttrs);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(info -> {
            Long spuId = info.getSpuId();

            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(spuId);
            skuItem.setDesc(spuInfoDesc);
        }, executor);

        CompletableFuture<Void> groupAttrsFuture = infoFuture.thenAcceptAsync(info -> {
            Long spuId = info.getSpuId();
            Long catalogId = info.getCatalogId();

            List<SkuItemVo.SpuItemAttrGroupVo> spuItemAttrGroups = attrGroupService.getAttrGroupWithAttrsBySpuId(spuId, catalogId);
            skuItem.setGroupAttrs(spuItemAttrGroups);
        }, executor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImages = skuImagesService.getImagesBySkuId(skuId);
            skuItem.setImages(skuImages);
        }, executor);


        CompletableFuture.allOf(saleAttrFuture, descFuture, groupAttrsFuture, imagesFuture).get();

        return skuItem;
    }

    @Override
    public BigDecimal getPriceBySkuId(Long skuId) {
        SkuInfoEntity skuInfo = this.getOne(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuId));

        return skuInfo.getPrice();
    }

}